package com.idealighter.game.games.horserace.manager;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import com.idealighter.game.dictionary.dic.HorseRaceRoomDic;
import com.idealighter.game.dictionary.domain.HorseRaceRoomDomain;
import com.idealighter.game.games.common.AbstractTable;
import com.idealighter.game.games.horserace.struct.HorseRaceRoom;
import com.idealighter.game.games.horserace.struct.HorseRaceSeat;
import com.idealighter.game.games.horserace.struct.HorseRaceTable;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 赛马数据管理.
 */
@Singleton
public class HorseRaceDataMgr {

  private static final Logger LOG = LoggerFactory.getLogger(HorseRaceDataMgr.class);

  private final HorseRaceRoomDic roomDic;
  private final Map<Integer, HorseRaceRoom> rooms;

  // 玩家的座位
  private final Map<Long, HorseRaceSeat> playerSeats = new HashMap<>();

  @Inject
  public HorseRaceDataMgr(HorseRaceRoomDic roomDic) {
    this.roomDic = roomDic;
    this.rooms = createRooms();
  }

  /**
   * 创建房间.
   * 
   * @return 房间map.
   */
  private Map<Integer, HorseRaceRoom> createRooms() {
    Map<Integer, HorseRaceRoom> rooms = new HashMap<>();
    for (HorseRaceRoomDomain roomDom : roomDic.list()) {
      rooms.put(roomDom.getId(), new HorseRaceRoom(roomDom));
      LOG.info("[赛马]创建房间[{}][{}]", roomDom.getId(), roomDom.getName());
    }

    return rooms;
  }

  /**
   * 获取座位.
   * 
   * @param playerId 玩家id. 房间Id.
   * @return 座位.
   */
  public HorseRaceSeat getPlayerSeat(long playerId) {

    return playerSeats.get(playerId);
  }

  /**
   * 更新玩家座位.
   * 
   * @param playerId 玩家id. 房间Id.
   * @param seat 座位信息. 座位.
   */
  public void updatePlayerSeats(long playerId, HorseRaceSeat seat) {
    playerSeats.put(playerId, seat);
  }

  /**
   * 移除玩家seat.
   * 
   * @param playerId 玩家id. 玩家Id.
   */
  public void removePlayerSeat(long playerId) {
    playerSeats.remove(playerId);
  }

  /**
   * 获取房间.
   * 
   * @param roomId . 房间Id.
   * @return 房间.
   */
  public HorseRaceRoom getRoom(int roomId) {

    return rooms.get(roomId);
  }

  /**
   * 获取所有房间集合.
   * 
   * @return 房间列表.
   */
  public Collection<HorseRaceRoom> rooms() {

    return rooms.values();
  }

  /**
   * 获取牌桌.
   * 
   * @param tableId . 桌子Id.
   * @return 桌子.
   */
  public HorseRaceTable getTable(int tableId) {
    HorseRaceRoom room = getRoom(roomId(tableId));

    if (room == null) {
      return null;
    } else {
      return room.tables.get(tableId);
    }
  }

  /**
   * 根据桌子id计算房间id.
   * 
   * @param tableId . 桌子Id.
   * @return 房间Id.
   */
  public int roomId(int tableId) {

    return tableId / AbstractTable.MAX_TABLE;
  }
}
